import { useState, useEffect } from 'react';
import { Toast } from './Toast';
import { ToastContainerProps, Toast as ToastType } from './types';

export const ToastContainer = ({ 
  position = 'bottom-right', 
  autoClose = true, 
  autoCloseTime = 10000 
}: ToastContainerProps) => {
  const [toasts, setToasts] = useState<ToastType[]>([]);

  // 监听自定义事件，用于添加新的Toast
  useEffect(() => {
    const handleAddToast = (event: CustomEvent) => {
      const toast = event.detail;
      
      if (toast) {
        // 设置默认duration
        if (autoClose && !toast.duration) {
          toast.duration = autoCloseTime;
        }
        
        setToasts(prevToasts => [...prevToasts, toast]);
      }
    };

    // 监听全局事件
    window.addEventListener('addToast' as any, handleAddToast as EventListener);
    
    return () => {
      window.removeEventListener('addToast' as any, handleAddToast as EventListener);
    };
  }, [autoClose, autoCloseTime]);

  // 关闭指定Toast
  const handleClose = (id: string) => {
    setToasts(prevToasts => 
      prevToasts.map(toast => 
        toast.id === id 
          ? { ...toast, closing: true } 
          : toast
      )
    );
    
    // 添加动画延迟，在动画结束后移除
    setTimeout(() => {
      setToasts(prevToasts => 
        prevToasts.filter(toast => toast.id !== id)
      );
    }, 500); // 匹配动画时间
  };

  // 根据position设置容器位置
  const getPositionClasses = () => {
    switch (position) {
      case 'top-right':
        return 'top-4 right-4';
      case 'top-left':
        return 'top-4 left-4';
      case 'bottom-left':
        return 'bottom-4 left-4';
      case 'bottom-right':
      default:
        return 'bottom-4 right-4';
    }
  };

  return (
    <div 
      className={`fixed z-50 flex flex-col ${getPositionClasses()}`}
    >
      {toasts.map(toast => (
        <Toast 
          key={toast.id} 
          toast={toast} 
          onClose={handleClose} 
        />
      ))}
    </div>
  );
}; 